import 'dart:async';


import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:animated_tree_view/animated_tree_view.dart' as treeview;
import 'package:yuellyfactory/components/NoScrollbarBehavior.dart';
import 'package:yuellyfactory/eventbus/EventRefreshType.dart';
import 'package:yuellyfactory/util/ColorUtil.dart';
import 'package:yuellyfactory/util/DialogUtil.dart';
import 'package:yuellyfactory/util/GlobalData.dart';
import 'package:yuellyfactory/util/ViewUtil.dart';

import 'package:yuellyfactory/views/dto/PricePart.dart';
import 'package:yuellyfactory/views/model/EditMaterialView.dart';
import 'package:yuellyfactory/views/model/EditTypeView.dart';
import 'package:yuellyfactory/views/model/ModelConfigVC.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../eventbus/EventRefreshMaterial.dart';
import '../../eventbus/EventRefreshTree.dart';
import '../../util/BaseRequest.dart';
import '../../util/ToastUtil.dart';
import '../dto/PopupAction.dart';

class ModelVC extends StatefulWidget {
  const ModelVC({super.key});

  @override
  State<ModelVC> createState() => _ModelVCState();
}

class _ModelVCState extends State<ModelVC> {

  treeview.TreeViewController? _controller;
  final formKey = GlobalKey<ShadFormState>();
  var currentSelect = "";
  final dialogKey = GlobalKey<ShadFormState>();
  StreamSubscription? streamSubscription;
  StreamSubscription? treeStreamSubscription;
  PricePart ?selectPricePart;
  List allDatas=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getAllData();
    streamSubscription = eventBus.on<EventRefreshBase>().listen((event) {
      getAllData();
    });
    treeStreamSubscription=eventBus.on<EventRefreshTree>().listen((event){
      if(event.id.isNotEmpty){
        currentSelect=event.id;
        selectPartById(currentSelect);
        if(selectPricePart!.type!="product"){

          treeview.ListenableNode node=sampleTree.elementAt(selectPricePart!.path);
          _expandNodes(node as treeview.TreeNode,true);
        }else{
         var path= selectPricePart!.path.substring(0,selectPricePart!.path.lastIndexOf("."));

          treeview.ListenableNode node=sampleTree.elementAt(path);
          _expandNodes(node as treeview.TreeNode,true);
        }
        setState(() {

        });
        if(selectPricePart!.type=='type'||selectPricePart!.type=='serial'){
          eventBus.fire(EventRefreshType(selectPricePart!));
        }else{
          eventBus.fire(EvetnRefreshMaterial(selectPricePart!));
        }


      }

    });
  }


  void _expandNodes(
      treeview.TreeNode preselectedNode,
      bool directionRootToNode) {
    final String path = preselectedNode.path;
    // example path: 623c79a5-3ae9-4706-bad0-7dd8093f3d1b.01JQPXYM0EMS9CMMRHM84Y9RZK.01JQPXYM0EJE7RHGMYV2V92CR3

    // Split the path by the dot separator to get individual node IDs
    final List<String> nodeIds = path.split(".");

    if (nodeIds.length >= 2) {
      // Generate all the paths from shortest (root) to longest (preselected node's parent)
      List<String> pathsToExpand = [];

      // Build all possible paths from root to the target node (excluding the target itself)
      for (int i = 1; i < nodeIds.length; i++) {
        // Creating paths of increasing length, starting from the root
        String currentPath = nodeIds[0];
        for (int j = 1; j < i; j++) {
          currentPath = "$currentPath.${nodeIds[j]}";
        }
        pathsToExpand.add(currentPath);
      }

      // If we're expanding from root to node, use the paths as they are (top-down)
      // If expanding from node to root, reverse the order (bottom-up)
      if (!directionRootToNode) {
        // Reverse the list to go from bottom up (nearest ancestor first)
        pathsToExpand = pathsToExpand.reversed.toList();
      }

      // Now expand the nodes in the appropriate order based on directionRootToNode
      for (final String nodePath in pathsToExpand) {
        final currentNode = _controller!.elementAt(nodePath);
        _controller!.expandNode(currentNode);
      }
    }
  }

  @override
  void dispose() {
    if (streamSubscription != null) {
      streamSubscription!.cancel();
    }
    if (treeStreamSubscription != null) {
      treeStreamSubscription!.cancel();
    }
    super.dispose();
  }





  selectPartById(String id){
    for(PricePart type in allDatas){
      if(id==type.id){
        selectPricePart=type;
        break;
      }
      for(PricePart brand in type.priceModels){
        if(brand.id==id){
          selectPricePart=brand;
          break;
        }

        for(PricePart serial in brand.priceModels){
          if(serial.id==id){
            selectPricePart=serial;
            break;
          }

        }

      }

    }
  }

  var sampleTree = treeview.TreeNode.root();

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Container(
      child: DecoratedBox(
        decoration: BoxDecoration(
          borderRadius: theme.radius,
          border: Border.all(
            color: theme.colorScheme.border,
          ),
        ),
        child: ClipRRect(
          borderRadius: theme.radius,
          child: ShadResizablePanelGroup(
            children: [
              ShadResizablePanel(
                defaultSize: .2,
                minSize: .1,
                maxSize: .5,
                child:
                Card(
                  color: Colors.white,
                  child:
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        SizedBox(height: ViewUtil.screenHeight(10),),
                        Row(
                          children: [
                            SizedBox(width: ViewUtil.screenWidth(10),),
                            Text('机型数据',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                            Expanded(child: Container(),),
                            ViewUtil.addIcon("新增分类", (){
                              addType();
                            }),

                          ],
                        ),

                        // SizedBox(height: ViewUtil.screenHeight(10),),
                        Expanded(child: treeview.TreeView.simple(
                            showRootNode: false,
                            focusToNewNode: false,
                            expansionIndicatorBuilder: (context, node) {
                              return treeview.ChevronIndicator.rightDown(
                                tree: node,
                                alignment: Alignment.centerRight,
                                color:ColorUtil.colorBlue,
                              );
                            },
                            indentation: const treeview.Indentation(

                                style: treeview.IndentStyle.roundJoint),
                            onItemTap: (item) {
                              print("Item tapped: ${item.key}");
                              currentSelect = item.key;
                              selectPricePart=item.data;
                              print("Item tapped: ${selectPricePart!.type}");
                              setState(() {}
                              );
                              if(selectPricePart!.type=='type'||selectPricePart!.type=='serial'){
                                eventBus.fire(EventRefreshType(selectPricePart!));
                              }else{
                                eventBus.fire(EvetnRefreshMaterial(selectPricePart!));
                              }
                            },
                            onTreeReady: (controller) {
                              _controller = controller;
                            },
                            builder: (context, node) =>
                                Container(
                                  decoration: BoxDecoration(
                                    color: currentSelect == node.key ? Colors.blue
                                        .withOpacity(0.1) : null,
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  child: ListTile(
                                    title: Text("${node.data.name}",style: TextStyle(fontSize: ViewUtil.fontSize(22)),),
                                    trailing:node.data.type=='part'?null:
                                    PopupMenuButton<int>(
                                      color: Colors.white,
                                      tooltip: '',
                                      // 三点按钮的图标
                                      icon: const Icon(Icons.more_vert,color: Colors.grey,),
                                      // 下拉菜单的位置
                                      offset: const Offset(0, 50),
                                      itemBuilder: (context) => _buildPopupMenuItems(node.data),
                                      // 点击菜单项的回调
                                      onSelected: (value) {
                                        debugPrint(value.toString());
                                        switch (value) {

                                          case 1:{
                                            editType(node.data);
                                            break;
                                          }

                                          case 2:{
                                            addSerial();
                                            break;
                                          }
                                          case 3:{
                                            addProductType();
                                            break;
                                          }
                                          case 4:{
                                           // getAllParts();
                                            configModel();
                                            break;
                                          }
                                          case 5:{
                                            DialogUtil.showConfimDialog(context, "确定删除${node.data.name}", "确定将删除${node.data.name}", "确定", (){
                                              uploadDelModel(node.data);
                                            });

                                            break;
                                          }
                                          case 6:{
                                            DialogUtil.showConfimDialog(context, "确定删除${node.data.name}", "确定将删除${node.data.name}", "确定", (){
                                              uploadDelModel(node.data);
                                            });
                                            break;
                                          }
                                          case 7:{
                                            DialogUtil.showConfimDialog(context, "确定删除${node.data.name}", "确定将删除${node.data.name}", "确定", (){
                                              uploadDelModel(node.data);
                                            });
                                            break;
                                          }

                                        }
                                      },
                                    ),
                                  ),
                                ),
                            tree: sampleTree),)
                      ],
                    )

                ),

              ),
              ShadResizablePanel(

                defaultSize: .8,
                child:

                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [

                    Expanded(
                      child: Card(color: Colors.white,
                        child:
                        ScrollConfiguration(
                          behavior: NoScrollbarBehavior(),
                          child: SingleChildScrollView(
                            child:
                            Padding(
                              padding: const EdgeInsets.all(5.0),
                              child:
                                  Column(children: [
                                    Visibility(
                                        visible: selectPricePart==null,
                                        child: Container()),

                                    Visibility(
                                      maintainState: true,
                                        visible: selectPricePart!=null&&(selectPricePart!.type=='type'||selectPricePart!.type=='serial'),
                                        child: EditTypeView()),
                                    Visibility(
                                      maintainState: true,
                                        visible: selectPricePart!=null&&(selectPricePart!.type=='product'),
                                        child: EditMaterialView())
                                  ],),
                            ),),
                        ),

                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }




  // 动态构建菜单项的方法
  List<PopupMenuItem<int>> _buildPopupMenuItems(PricePart partData) {
    selectPricePart=partData;
    currentSelect=partData.id;
    setState(() {

    });
    // 这里可以根据实际需求动态生成菜单项列表
    // 示例：从数据源获取或根据条件生成
    final List<PopupAction> actions = [
      if(selectPricePart!=null&&selectPricePart!.type=='type')
        PopupAction(
          value: 1,
          label: "编辑分类",
        ),

      if(selectPricePart!=null&&selectPricePart!.type=='type')
        PopupAction(
          value: 5,
          label: "删除分类",
        ),
      if(selectPricePart!=null&&selectPricePart!.type=='type')
        PopupAction(
          value: 2,
          label: "新增产品系列",
        ),

      // 可以根据条件动态添加菜单项
      if(selectPricePart!=null&&selectPricePart!.type=='serial')
        PopupAction(
          value: 3,
          label: "新增机型",

        ),
      if(selectPricePart!=null&&selectPricePart!.type=='serial')
      PopupAction(
        value: 6,
        label: "删除产品系列",

      ),
      if(selectPricePart!=null&&selectPricePart!.type=='product')
        PopupAction(
          value: 4,
          label: "型号配置",

        ),
      if(selectPricePart!=null&&selectPricePart!.type=='product')
      PopupAction(
        value: 7,
        label: "删除机型",

      ),
      // if(partData.parentId!='0')
      //   PopupAction(
      //     value: 5,
      //     label: "新增型号",
      //
      //   ),
    ];

    return actions.map((action) {
      return PopupMenuItem<int>(
        value: action.value,
        child: Row(
          children: [

            const SizedBox(width: 8),
            Text(action.label),
          ],
        ),
      );
    }).toList();
  }


  void addPart(var options) {
    //选择零件列表。
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitPart();
            },)
            ],
            child:
            ShadForm(
              key: dialogKey,
              child:

              ShadSelectFormField<String>(
                id: 'part',

                label: const Text('分类'),
                minWidth: 350,
                options: (options as Map).entries
                    .map((e) => ShadOption(value: e.key.toString(), child: Text(e.value.toString())))
                    .toList(), // 注意添加toList()转换
                selectedOptionBuilder: (context, value) {
                  if (value == null || value == 'none') {
                    return const Text('请选择分类');
                  }
                  // 使用空值合并运算符??代替!，提供默认值
                  return Text((options as Map)[value]?.toString() ?? '未知选项');
                },
                placeholder: const Text('请选择分类'),
                validator: (v) {
                  if (v == null) {
                    return '请选择分类';
                  }
                  return null;
                },
              ),

            )

        )
    );


  }

  //添加配件
  void submitPart(){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var part = values["part"];
      var parm = {
        "modelId": selectPricePart!.id,
        "partId": part,
        "type":"type",
      };
      BaseRequest.postHttp('price/addconfigpart', parameters: parm,
          canTip: true,
          context: context,
          onSuccess: (data) {
            bool result = BaseRequest.chekResponse(data, true);
            if (result) {
              ToastUtil.showToast("添加成功");
              getAllData();
              Navigator.pop(context);
            }
          },
          onError: (error) {

          });
    }
  }



  void addProductType() {
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitProductType();
            },)
            ],
            child:
            ShadForm(
              key: dialogKey,
              child: Column(
                children: [
                  ShadInputFormField(
                    id: 'name',
                    label: const Text('机型名称'),
                    placeholder: const Text('请输入机型名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入机型名称';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'code',
                    label: const Text('Code'),
                    placeholder: const Text('请输入Code'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入Code';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'grossMargin',
                    label: const Text('毛利率(如10%,直接输入10'),
                    suffix: const Text("%"),
                    placeholder: const Text('请输入毛利率'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入毛利率';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'profitMargin',
                    label: const Text('利润率(如10%,直接输入10'),
                    suffix: const Text("%"),
                    placeholder: const Text('请输入利润率'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入利润率';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'retailRatio',
                    label: const Text('零售价比例(如10%,直接输入10'),
                    suffix: const Text("%"),
                    placeholder: const Text('请输入零售价比例'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入零售价比例';
                      }
                      return null;
                    },
                  ),
                ],
              )

            )

        )
    );
  }

  void addSerial() {
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitSerial();
            },)
            ],
            child:
            ShadForm(
              key: dialogKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('新增产品系列'),
                placeholder: const Text('请输入产品系列名称'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入产品系列名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }


  void addType() {
    showShadDialog(context: context, builder: (context) =>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'), onPressed: () {
              submitAddType();
            },)
            ],
            child:
            ShadForm(
              key: dialogKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('新增分类'),
                placeholder: const Text('请输入分类名称'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入分类名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }

  void submitProductType(){

      if (dialogKey.currentState!.saveAndValidate()) {
        var values = dialogKey.currentState!.value;
        var name = values["name"];
        var code= values["code"];
        var grossMargin=values["grossMargin"];
        var profitMargin=values["profitMargin"];
        var retailRatio=values["retailRatio"];
        var parm = {
          "name": name,
          "code": code,
          "grossMargin":grossMargin,
          "profitMargin":profitMargin,
          "retailRatio":retailRatio,
          "parentId": selectPricePart!.id,
          "type": "product",
        };
        BaseRequest.postHttp('price/edittype', parameters: parm,
            canTip: true,
            context: context,
            onSuccess: (data) {
              bool result = BaseRequest.chekResponse(data, true);
              if (result) {
                ToastUtil.showToast("添加成功");
                getAllData();
                Navigator.pop(context);
              }
            },
            onError: (error) {

            });
      }

  }

  void submitSerial(){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var name = values["name"];
      var parm = {
        "name": name,
        "parentId": selectPricePart!.id,
        "type": "serial",
      };
      BaseRequest.postHttp('price/edittype', parameters: parm,
          canTip: true,
          context: context,
          onSuccess: (data) {
            bool result = BaseRequest.chekResponse(data, true);
            if (result) {
              ToastUtil.showToast("添加成功");
              getAllData();
              Navigator.pop(context);
            }
          },
          onError: (error) {

          });
    }
  }


  void submitAddType() {
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var name = values["name"];
      var parm = {
        "name": name,
        "parentId": "0",
        "type": "type",
      };
      BaseRequest.postHttp('price/edittype', parameters: parm,
          canTip: true,
          context: context,
          onSuccess: (data) {
            bool result = BaseRequest.chekResponse(data, true);
            if (result) {
              ToastUtil.showToast("添加成功");
              getAllData();
              Navigator.pop(context);
            }
          },
          onError: (error) {

          });
    }
  }

  void getAllData() {
    BaseRequest.postHttp("price/allmodels", parameters: {},
        canTip: false,
        context: context,
        onSuccess: (data) {
          bool result = BaseRequest.chekResponse(data, true);
          if (result) {
            dynamic datas = data["data"];

            List allModel = [];
            for (var i = 0; i < datas.length; i++) {
              var item = datas[i];
              var part = PricePart.fromJson(item);
              allModel.add(part);
            }
            allDatas=allModel;
            GlobalData.modelData=allDatas;
            initTreeDatas(allModel);
          }
        },
        onError: (error) {

        });
  }

  void initTreeDatas(List allModel) {
    var trees = treeview.TreeNode.root();
    for (PricePart priceModel in allModel) {
      if(currentSelect==''){
        currentSelect=priceModel.id;
        selectPricePart=priceModel;
      }else{
        if(currentSelect==priceModel.id){
          selectPricePart=priceModel;
        }
      }
      priceModel.path=priceModel.id;
      treeview.TreeNode node = treeview.TreeNode(
          key: priceModel.id, data: priceModel);

      //第二级
      for(PricePart secondPart in priceModel.priceModels){
        if(currentSelect==secondPart.id){
          selectPricePart=secondPart;
        }
        secondPart.path="${priceModel.id}.${secondPart.id}";
        treeview.TreeNode secondNode=treeview.TreeNode(key: secondPart.id,data: secondPart);
        for(PricePart thirdPart in secondPart.priceModels) {
          if(currentSelect==thirdPart.id){
            selectPricePart=thirdPart;
          }
          thirdPart.path="${priceModel.id}.${secondPart.id}.${thirdPart.id}";
          treeview.TreeNode thirdNode=treeview.TreeNode(key: thirdPart.id,data: thirdPart);
          for(PricePart fourPart in thirdPart.priceParts){
            if(currentSelect==fourPart.id){
              selectPricePart=fourPart;
            }
            treeview.TreeNode fourNode=treeview.TreeNode(key: fourPart.id,data: fourPart);
            thirdNode.add(fourNode);
          }


          secondNode.add(thirdNode);
        }
        node.add(secondNode);

      }
      trees.add(node);
    }
    sampleTree = trees;
    setState(() {

    });
    if(selectPricePart!.type=='type'||selectPricePart!.type=='serial'){
      eventBus.fire(EventRefreshType(selectPricePart!));
    }else{
      eventBus.fire(EvetnRefreshMaterial(selectPricePart!));
    }
  }

  void getAllParts(){
    BaseRequest.postHttp("price/getallparts",parameters: {}, canTip: true, context: context, onSuccess: (data){
      bool result = BaseRequest.chekResponse(data, true);
      if (result) {
        dynamic datas = data["data"];

        var items={};
        for (var i = 0; i < datas.length; i++) {
          var item = datas[i];
          var id=item["id"];
          var name=item["name"];
          items[id]=name;
        }
        addPart(items);

      }
    }, onError: (error){

    });
  }


  void configModel(){
    showShadSheet(
      side: ShadSheetSide.right,
      context: context,
      builder: (context) => ModelConfigVC(callback: (){}, pricePart: selectPricePart!)

      ,
    );
  }


  void uploadDelModel(PricePart partData){
    var parm={
      "id":partData.id,

    };
    BaseRequest.postHttp("price/modeldel",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        getAllData();

      }
    }, onError: (error){

    });
  }



  void editType(PricePart partData){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitType(partData);
            },)],
            child:
            ShadForm(
              key: formKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('名称'),
                placeholder: const Text('请输入名称'),
                initialValue: partData.name,
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }





  void submitType(PricePart partData) {
    if (formKey.currentState!.saveAndValidate()) {
      var values = formKey.currentState!.value;
      var name = values["name"];
      var parm = {
        "name": name,
        "parentId": partData.parentId,
        "type": partData.type,
        "id":partData.id,
      };
      BaseRequest.postHttp('price/edittype', parameters: parm,
          canTip: true,
          context: context,
          onSuccess: (data) {
            bool result = BaseRequest.chekResponse(data, true);
            if (result) {
              ToastUtil.showToast("编辑成功");
              getAllData();
              Navigator.pop(context);
            }
          },
          onError: (error) {

          });
    }
  }
}